<template>
  <q-input class="q-px-sm" v-model="text" filled type="textarea" rows="20" label="多行文本转一行" />
  <div class="q-pa-md q-gutter-sm" style="text-align: center;">
    <q-btn class="color-btn" size="small" label="转换并复制" @click="format_text_rows_to_one" />
    <q-btn class="color-second-btn" size="small" label="清空" @click="clear" />
  </div>
  <div class="row q-gutter-sm items-center justify-center">
    <div>
      <q-item-label>{{ text_a }}</q-item-label>
      <q-item-label>{{ text_b }}</q-item-label>
    </div>
    <div class="q-px-sm">
      <q-icon name="double_arrow" />
    </div>
    <q-input class="float-left" v-model="flags.start_flag" style="width: 20px;" />
    <q-input class="float-left" v-model="text_a" readonly style="max-width: 40px;" />
    <q-input class="float-left" v-model="flags.middle_flag" style="width: 20px;" />
    <q-input class="float-left" v-model="text_b" readonly style="max-width: 40px;" />
    <q-input class="float-left" v-model="flags.end_flag" style="width: 20px;" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useQuasar } from 'quasar'

import { copyTextToClipboard } from '../utils/utils'

const $q = useQuasar()


const text_a = ref('AAA')
const text_b = ref('BBB')

const flags = ref({
  start_flag: '',
  middle_flag: ',',
  end_flag: ''
})

const text = ref('')

// 格式化数据并写入粘贴板
const format_text_rows_to_one = () => {
  if (!text.value) {
    $q.notify({
      position: 'top',
      type: 'warning',
      message: '请填写数据!'
    })
  } else {
    let new_data = flags.value.start_flag + text.value.replace(/\n/g, flags.value.middle_flag) + flags.value.end_flag;
    text.value = new_data
    copyTextToClipboard(new_data)
    $q.notify({
      position: 'top',
      type: 'positive',
      message: '已复制到剪贴板'
    })
  }
}

const clear = () => {
  text.value = ''
}

// 获取标识符
const get_flags = async () => {
  const { data } = await $q.bex.send('storage.get', { key: 'my_tool_flags' })
  if (data) {
    flags.value = data
  }
}
// 写入标识符到storage
const set_flags = async () => {
  const { data } = await $q.bex.send('storage.set', { key: 'my_tool_flags', value: flags.value })
}
// 挂载时获取标识
onMounted(() => {
  get_flags()
})
// 监控标识的修改
watch(flags, () => {
  set_flags()
}, { deep: true })
</script>